package com.yaoweigroup.community.ui.home;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.adapter.SelectAdapter;
import com.yaoweigroup.community.adapter.SportAdapter;
import com.yaoweigroup.community.adapter.SportGridViewAdapter;
import com.yaoweigroup.community.config.Constant;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.enity.SportShop;
import com.yaoweigroup.community.enity.SportTime;
import com.yaoweigroup.community.enity.SportType;
import com.yaoweigroup.community.enity.UserInfo;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.SharePreferenceUtil;
import com.yaoweigroup.community.util.UtilHttp;

/**
 * 文体活动
 * 
 * @author xi
 * 
 */
public class SportActivity extends Activity implements OnClickListener {

	private RelativeLayout left_rl;
	private PullToRefreshListView listView;
	private SportAdapter adapter;
	private List<SportShop> list;

	private TextView prj_tv;
	private TextView date_tv;
	private RelativeLayout prj_rl;
	private RelativeLayout date_rl;
	private List<String> prjList;
	private List<String> dateList;
	private List<SportType> sportTypes;
	private List<SportTime> sportTimes;

	private RelativeLayout type_rl;
	private ListView type_listView;
	private SelectAdapter selectAdapter;
	private SharePreferenceUtil prfUtil;
	private UserInfo userInfo;

	private ObjectMapper mapper;
	private ImageView error_iv;
	private ProgressBar progress;

	private List<SportShop> sportShops;

	private GridView tagView;
	private SportGridViewAdapter gridAdapter;
	private Button btn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sport);
		tagView = (GridView) findViewById(R.id.tagView);
		error_iv = (ImageView) findViewById(R.id.error_iv);
		progress = (ProgressBar) findViewById(R.id.progress);
		mapper = new ObjectMapper();
		prfUtil = new SharePreferenceUtil(this, Constant.prf);
		type_rl = (RelativeLayout) findViewById(R.id.type_rl);
		type_listView = (ListView) findViewById(R.id.type_listView);
		prjList = new ArrayList<String>();
		dateList = new ArrayList<String>();
		selectAdapter = new SelectAdapter(this, prjList);
		type_listView.setAdapter(selectAdapter);
		prj_rl = (RelativeLayout) findViewById(R.id.prj_rl);
		prj_rl.setOnClickListener(this);
		date_rl = (RelativeLayout) findViewById(R.id.date_rl);
		date_rl.setOnClickListener(this);
		date_tv = (TextView) findViewById(R.id.date_tv);
		prj_tv = (TextView) findViewById(R.id.prj_tv);
		type_rl.setOnTouchListener(typeSelectTouchListener);
		list = new ArrayList<SportShop>();
		adapter = new SportAdapter(this, list);
		gridAdapter = new SportGridViewAdapter(this, list);
		tagView.setAdapter(gridAdapter);
		btn = (Button) findViewById(R.id.btn);
		btn.setOnClickListener(this);
		btn.setVisibility(View.GONE);
		tagView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				selectSport = list.get(arg2);
				gridAdapter.setPosition(arg2);
			}
		});

		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				finish();
			}
		});

		listView = (PullToRefreshListView) findViewById(R.id.listView);
		listView.setAdapter(adapter);

		type_listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				if (type == 0) {

					siteType = sportTypes.get(position).getSiteTypeName();
					prj_tv.setText(siteType);
					guid = sportTypes.get(position).getGuid();
				} else {
					dateStr = sportTimes.get(position).getYmday();
					date_tv.setText(dateStr);
				}
				type_rl.setVisibility(View.GONE);
				progress.setVisibility(View.VISIBLE);
				error_iv.setVisibility(View.GONE);
				list.clear();
				selectSport = null;
				gridAdapter.setDataChange(list);
				getSeatOrderList();
			}
		});

	}

	OnTouchListener typeSelectTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			type_rl.setVisibility(View.GONE);
			return true;

		}
	};

	protected void onResume() {
		initData();
		super.onResume();
	};

	private void initData() {

		selectAdapter.setDataChange(prjList);
		login();

	}

	private int type = 0;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.prj_rl:
			if (type == 0 && type_rl.getVisibility() == View.VISIBLE) {
				type_rl.setVisibility(View.GONE);
			} else {
				type_rl.setVisibility(View.VISIBLE);
			}
			type = 0;
			selectAdapter.setDataChange(prjList);
			break;
		case R.id.date_rl:
			if (type == 1 && type_rl.getVisibility() == View.VISIBLE) {
				type_rl.setVisibility(View.GONE);
			} else {
				type_rl.setVisibility(View.VISIBLE);
			}
			type = 1;
			selectAdapter.setDataChange(dateList);
			break;
		case R.id.btn:
			Intent intent = new Intent(SportActivity.this,
					SportBookActivity.class);
			intent.putExtra("guid", selectSport.getGuid());
			startActivity(intent);
			break;
		}
	}

	public final int TYPE_SUCCESS = 0x2210;
	public final int TYPE_FAIL = TYPE_SUCCESS + 1;
	public final int TYPE_UBNIND_NAME = TYPE_SUCCESS + 2;

	public final int TIME_SUCCESS = TYPE_SUCCESS + 3;
	public final int TIME_FAIL = TYPE_SUCCESS + 4;
	public final int LOGIN_FAIL = TYPE_SUCCESS + 5;
	public final int LOGIN_SUCCESS = TYPE_SUCCESS + 6;

	public final int DATA_SUCCESS = TYPE_SUCCESS + 7;
	public final int DATA_FAIL = TYPE_SUCCESS + 8;

	private void login() {

		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("UserName", "admin");
		jsonUtil.add("PassWord", "123123");
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.login, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String data = obj.getString("data");
							String message = obj.getString("message");
							if (state == 200) {

								userInfo = mapper.readValue(data,
										new TypeReference<UserInfo>() {
										});
								handler.sendEmptyMessage(LOGIN_SUCCESS);

							} else {
								Message msg = handler.obtainMessage();
								msg.what = LOGIN_FAIL;
								msg.obj = message;
								handler.sendMessage(msg);
							}
						} catch (Exception e) {
							LogUtil.e("wxf", e.toString());
							handler.sendEmptyMessage(LOGIN_FAIL);
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(LOGIN_FAIL);
					}

				});
	}

	private void getType() {

		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		StringEntity enity = null;
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("Uid", userInfo.getUid());
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getSiteTypeList, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "type=" + responseInfo.result);
						try {
							JSONObject object = new JSONObject(
									responseInfo.result);
							int state = object.getInt("state");
							String data = object.getString("Data");
							if (state == 200) {
								sportTypes = mapper.readValue(data,
										new TypeReference<List<SportType>>() {

										});
								handler.sendEmptyMessage(TYPE_SUCCESS);

							} else {
								handler.sendEmptyMessage(TYPE_FAIL);

							}
						} catch (Exception e) {
							handler.sendEmptyMessage(TYPE_FAIL);

							LogUtil.e("wxf", e.toString());
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", "getType=" + error + "," + msg);
						handler.sendEmptyMessage(TYPE_FAIL);

					}

				});
	}

	/**
	 * time
	 */
	private void obtainTime() {
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		StringEntity enity = null;
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("Uid", userInfo.getUid());
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getNextOneWeek, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "time=" + responseInfo.result);
						try {
							JSONObject object = new JSONObject(
									responseInfo.result);
							int state = object.getInt("state");
							String data = object.getString("Data");
							if (state == 200) {
								sportTimes = mapper.readValue(data,
										new TypeReference<List<SportTime>>() {

										});
								handler.sendEmptyMessage(TIME_SUCCESS);

							}
						} catch (Exception e) {
							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", "obtainTime=" + error + "," + msg);
					}

				});
	}

	private String dateStr = "";
	private String siteType = "";
	private String guid = "";

	/**
	 * 获取场管数据
	 */
	private void getSeatOrderList() {
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		StringEntity enity = null;
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("Uid", userInfo.getUid());
		jsonUtil.add("site_type", siteType);
		jsonUtil.add("date", dateStr);
		jsonUtil.add("seat_order_guid", guid);
		try {
			enity = new StringEntity(jsonUtil.toString(), "UTF-8");
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		LogUtil.d("wxf", jsonUtil.toString());
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getSeatOrderList, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "list=" + responseInfo.result);

						try {
							JSONObject obj = new JSONObject(responseInfo.result);
							int state = obj.getInt("state");
							if (state == 200) {

								JSONArray array = obj.getJSONArray("Data");
								if (array.length() > 0) {
									sportShops = mapper
											.readValue(
													array.getJSONObject(0)
															.getString("list"),
													new TypeReference<List<SportShop>>() {

													});
									handler.sendEmptyMessage(DATA_SUCCESS);
								} else {
									handler.sendEmptyMessage(DATA_FAIL);

								}

							} else {
								handler.sendEmptyMessage(DATA_FAIL);
							}
						} catch (Exception e) {
							LogUtil.e("wxf", "getSeatOrderList=" + e.toString());
							handler.sendEmptyMessage(DATA_FAIL);
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", "getSeatOrderList=" + error + ","
								+ msg);
						handler.sendEmptyMessage(DATA_FAIL);

					}

				});
	}

	private SportShop selectSport = null;
	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case TYPE_FAIL:

				break;
			case TYPE_SUCCESS:
				if (sportTypes != null && sportTypes.size() > 0) {

					for (SportType sportType : sportTypes) {
						prjList.add(sportType.getSiteTypeName());
					}
					siteType = sportTypes.get(0).getSiteTypeName();
					guid = sportTypes.get(0).getGuid();
					prj_tv.setText(siteType);
					selectAdapter.setDataChange(prjList);
				}
				obtainTime();
				break;
			case TYPE_UBNIND_NAME:

				break;
			case TIME_SUCCESS:

				if (sportTimes != null && sportTimes.size() > 0) {

					for (SportTime time : sportTimes) {
						dateList.add(time.getMday());
					}
					dateStr = sportTimes.get(0).getYmday();
					date_tv.setText(dateStr);
				}
				getSeatOrderList();
				break;
			case LOGIN_SUCCESS:
				getType();

				break;
			case LOGIN_FAIL:
				Toast.makeText(SportActivity.this, "获取失败", 500).show();
				finish();
				break;
			case DATA_FAIL:
				progress.setVisibility(View.GONE);
				error_iv.setVisibility(View.VISIBLE);
				break;
			case DATA_SUCCESS:
				list.clear();
				progress.setVisibility(View.GONE);
				if (sportShops != null && sportShops.size() > 0) {
					list.addAll(sportShops);
					adapter.setDataChange(list);
					gridAdapter.setPosition(0);
					selectSport = list.get(0);
					gridAdapter.setDataChange(list);
					btn.setVisibility(View.VISIBLE);
				} else {
					error_iv.setVisibility(View.VISIBLE);
				}

				break;
			}
		};
	};

}
